package com.ghyf.mplay;


import org.videolan.libvlc.LibVlcException;
import org.videolan.vlc.util.VLCInstance;

import com.example.watchdog.Watchdog;
import com.ghyf.mplay.application.CookieConstants;
import com.ghyf.mplay.application.UserInfoSingleton;
import com.ghyf.mplay.net.common.RecvBase;
import com.ghyf.mplay.net.shot.ScreenShotHttpServer;
import com.ghyf.mplay.service.PlayLogService;
import com.ghyf.mplay.service.RecvService;
import com.ghyf.mplay.service.RunLogService;
import com.ghyf.mplay.service.ScheduleService;
import com.ghyf.mplay.uimanager.ViewManager;
import com.ghyf.mplay.util.CommonUtil;
import com.ghyf.mplay.util.LogUtil;
import com.ghyf.mplay.util.ScreenShotFb;
import com.ghyf.mplay.value.ConstantValue;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;

/**
 * 
 * MPlayActivity 程序启动类 
 * @author cuiran
 * @version 1.0.0
 */
public class MPlayActivity  extends BaseActivity {
	private static final String TAG="MPlayActivity";
	private boolean isShow;// 导航栏是否隐藏
	private boolean isStop=false;
	private Watchdog dog=null;
	 
	static {
		    System.loadLibrary("watchdog");
	}
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
			try {

	            // Start LibVLC
	            VLCInstance.getLibVlcInstance();
	            // 调用ViewManagerd的init方法，将context传递过去。
	        	ViewManager.getInstance().init(this);
	    		// 隐藏导航条
	    		sendBroadcast(new Intent("com.android.action.HIDE_BAR"));
	    		isShow = false;
	    		// 初始化一些系统变量
	    		UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsPowerOff, false);
	    		UserInfoSingleton.putBooleanAndCommit(CookieConstants.GlobalAudioVolume,false);
	    		UserInfoSingleton.putBooleanAndCommit(CookieConstants.GlobalAudioStatus,false);
	    		UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsDownload, false);
	    		UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsDownloadFail, false);
	    		UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsRefresh, false);
	    		UserInfoSingleton.putIntAndCommit(CookieConstants.VideoStatus, ConstantValue.VIDEOSTATUS_YES);
	    		
	    		// 初始化截图服务
	    		ScreenShotFb.init(this);
	    		// 开启HttpServer
	    		ScreenShotHttpServer.start();
	    		// 创建WatchDog实例 【发布版本时候需要将以下注释打开，测试过程临时注释】
	    			//~~~~####### 【开始】###########
//	    		dog=Watchdog.getInstance();
//	    		int m=dog.openWatchdog(20);
//	    		if(m!=0){
//	    			LogUtil.i(TAG, "------------->>>>>>>>>>>>>>>看门狗打开失败...");
//	    		}
//	    		 LogUtil.i(TAG, " watchdog open ........result="+m);
//	    		watchDogHandler.sendEmptyMessageDelayed(1,10000);
	    			//~~~~####### 【结束】　###########
	    		
	    		//注册广播 	主要用于接收控制中心和程序内部的直播或本地切换广播
	    		IntentFilter myIntentFilter = new IntentFilter();
	    		myIntentFilter.addAction(RecvBase.ACTION_CMD_MAIN);
	    		//注册广播      
	    		registerReceiver(mainReceiver, myIntentFilter);
	    		
	    		
	        }
			catch (LibVlcException e) {
	        	LogUtil.e(TAG, " LibVlcException",e);
	        }
			catch (Exception e) {
	        	 LogUtil.e(TAG, "Exception",e);
	        }
	

	}
	/**
	 * 关闭打开的直播Activity
	 * 2014-11-28 上午9:42:07
	 *
	 */
	private void close(){
		if(null!=MLiveActivity.instance){
			MLiveActivity.instance.finish();
		}
		
	}
	/**
	 * 接收控制中心和程序内部的直播或本地切换广播
	 */
	 private final BroadcastReceiver mainReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				  String action = intent.getAction();
				  short cmd=intent.getShortExtra("cmd", (short)0);
				  LogUtil.i(TAG, "action="+action+",cmd="+cmd);
				  switch (cmd) {
				  case RecvBase.CMD_CONTROL_PLAYSTREAM:
						/**
						 * 直播~~~~~~~~~~启动直播播放器 隐藏本地播放器
						 */
					  change();//启用VLC
					  
//						UserInfoSingleton.setIslive(ConstantValue.PLAY_LIVE);
//						//先停止本地播放
//						ViewManager.getInstance().getlVideo().stopPlayback();
//						ViewManager.getInstance().getlVideo().setVisibility(View.GONE);
//						ViewManager.getInstance().getMyVideo().setVisibility(View.VISIBLE);
//						ViewManager.getInstance().getVitamioInfo().startPlay();
						break;
					case RecvBase.CMD_CONTROL_PLAYLOCAL:
						/**
						 * 本地~~~~~~~~~~启动本地播放器 隐藏直播播放器
						 */
						close();//关闭VLC
						
						
//						UserInfoSingleton.setIslive(ConstantValue.PLAY_LOCAL);
//						ViewManager.getInstance().getMyVideo().setVisibility(View.GONE);
//						ViewManager.getInstance().getMyVideo().stopPlayback();
//						
//						ViewManager.getInstance().getlVideo().setVisibility(View.VISIBLE);
//						ViewManager.getInstance().getVideoInfo().startPlay();
						break;
					default:
						break;
					}
				  
				
				
			}
			
	 };
	 /**
	  * 弹出直播画面
	  */
	private void change(){
		/**
		 * 弹出直播画面
		 */
		Intent intent1=new Intent(this, MLiveActivity.class);
		intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent1);
	}
	
	Runnable myRunnable=new Runnable() {
		
		@Override
		public void run() {
			change();
		}
	};
	
	/**
	 * 定时执行watchdog中的feedWatchdog
	 * @author cuiran
	 * @version 1.0.0
	 */
	 private static class WatchDogHandler extends WeakHandler<MPlayActivity> {
	        public WatchDogHandler(MPlayActivity owner) {
	            super(owner);
	        }
	        @Override
			public void handleMessage(Message msg) {
	         
	        	MPlayActivity activity = getOwner();
	        	if(activity == null) return;
				// sendAck
				if(!activity.isStop){
					int m=activity.dog.feedWatchdog();
					activity.watchDogHandler.sendEmptyMessageDelayed(1,3000);
					if(m<=0){
						LogUtil.i(TAG, "feed  watchdog fund error... m="+m);
					}
				}else{
					UserInfoSingleton.putBooleanAndCommit("isExit", true);
				}
				super.handleMessage(msg);
			}
	 }
		/**
		 * 创建 WatchDogHandler
		 */
	 private final Handler watchDogHandler = new WatchDogHandler(this);
	
	
	@Override
	protected void onResume() {
			
		LogUtil.i(TAG, "MPlayActivity onResume");
		String classname= ScheduleService.class.getName();
		if(!CommonUtil.isServiceRunning(this,classname)){
			Intent it = new Intent(this, ScheduleService.class);
			this.startService(it);// 启动服务
		}
		
		 classname= RecvService.class.getName();
			if(!CommonUtil.isServiceRunning(this,classname)){
				Intent it = new Intent(this, RecvService.class);
				this.startService(it);// 启动服务
			}
		
		 classname= PlayLogService.class.getName();
		if(!CommonUtil.isServiceRunning(this,classname)){
			Intent it = new Intent(this, PlayLogService.class);
			this.startService(it);// 启动服务
		}
		 classname= RunLogService.class.getName();
		 if(!CommonUtil.isServiceRunning(this,classname)){
				Intent it = new Intent(this, RunLogService.class);
				this.startService(it);// 启动服务
		 }

		   
		super.onResume();
	}


	@Override
	/**
	 * 监听鼠标的点击，进行导航栏的显示和隐藏。
	 */
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (isShow == false) {
				sendBroadcast(new Intent("com.android.action_DISPLAY_BAR"));
				isShow = true;
			} else {
				sendBroadcast(new Intent("com.android.action.HIDE_BAR"));
				isShow = false;
			}
		}
		return super.onTouchEvent(event);
	}
	
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		
		LogUtil.i(TAG, "MPlayActivity onPause");
		super.onPause();
	}
	@Override
	//activity 销毁时停止服务。
	protected void onDestroy() {
		try{	
			super.onDestroy();
			isStop=true;
			//取消注册广播     
			unregisterReceiver(mainReceiver);
			sendBroadcast(new Intent("com.android.action_DISPLAY_BAR"));
			LogUtil.i(TAG, "MPlayActivity onDestroy");
			if(dog!=null){
				dog.close();
			}
			ScreenShotHttpServer.stop();
			CommonUtil.reSoftWare(this);
			AppManager.getAppManager().AppExit(this);
			//~~~程序退出杀掉进程
//			int myPid = android.os.Process.myPid();
//			android.os.Process.killProcess(myPid); // 
			
			
		}catch(Exception e){
			LogUtil.e(TAG,"onDestroy",e);
		}
		
	}
	
	
}